package com.sky.controller.admin;


import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController("adminDishController")
@Slf4j
@RequestMapping("admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品信息
    @PostMapping("")
    public Result<String> addDish(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品:{}", dishDTO);
        dishService.addDishWithFlavor(dishDTO);
        return Result.success();
    }

    //菜品分页查询
    @GetMapping("/page")
    public Result<PageResult> getAllDish(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询菜品");
        PageResult dishPageResult = dishService.getAllDish(dishPageQueryDTO);
        return Result.success(dishPageResult);
    }

    //删除菜品
    @DeleteMapping()
    public Result<String> deleteDish(@RequestParam List<Long> ids) {//让mvc自己动
        /*
        1.可以一次删除一个菜品,也可以批量删除菜品
        2.起售中的菜品不能删除
        3.被套餐关联的菜品不能删除
        4.删除菜品后,关联的口味数据也要删除
        * */
        log.info("菜品批量删除{}", ids);
        dishService.deleteBatch(ids);
        cleanCache("dish_*");

        return Result.success();
    }

    //更新菜品上架状态
    @PostMapping("/status/{status}")
    public Result<String> updateDishStatus(@PathVariable("status") Integer status, Long id) {
        log.info("传入菜品数据:{},{}", status, id);
        dishService.updateDishStatus(status, id);
        cleanCache("dish_" + id);
        return Result.success();
    }

    //根据id查询菜品
    @GetMapping("/{id}")
    public Result<DishVO> getDishById(@PathVariable("id") Long id) {
        return Result.success(dishService.selectById(id));
    }

    //根据分类的id查询菜品
    @GetMapping("/list")
    public Result<List<Dish>> getDishByCategoryId(Long categoryId) {
        List<Dish> dishList = dishService.getDishByCategoryId(categoryId);
        return Result.success(dishList);
    }

    // 修改菜品信息
    @PutMapping("")
    public Result<String> updateDish(@RequestBody DishDTO dishDTO) {
        dishService.updateDishInfo(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }

    //清理缓存数据
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }


}
